﻿using System.Collections.Generic;

namespace RockBus.Threading
{
    internal class RoundRobinIndexDictionaryValue
    {
        public RoundRobinIndexDictionaryValue(int maxIndex)
        {
            this._maxIndex = maxIndex;
        }

        private int _currentIndex;

        private readonly int _maxIndex;

        public int MaxIndex { get { return this._maxIndex; } }

        private readonly object _indexLockObject = new object();

        internal int Increment()
        {
            // If anyone has a better idea? Can't use Interlocked.Increment here...
            lock (_indexLockObject)
            {
                this._currentIndex++;
                this._currentIndex %= this._maxIndex;
                return this._currentIndex;
            }
            //return Interlocked.Increment(ref this._currentIndex);
        }
    }

    public class RoundRobinIndexDictionary<TKey>
    {
        public RoundRobinIndexDictionary(int capacity)
        {
            this._indexDictionary = new Dictionary<TKey, RoundRobinIndexDictionaryValue>(capacity);
        }

        private readonly Dictionary<TKey, RoundRobinIndexDictionaryValue> _indexDictionary;

        public void Add(TKey key, int maxIndex)
        {
            this._indexDictionary.Add(key, new RoundRobinIndexDictionaryValue(maxIndex));
        }

        public int Increment(TKey key, int maxIndex)
        {
            if (!this._indexDictionary.ContainsKey(key))
            {
                this.Add(key, maxIndex);
            }
            return this._indexDictionary[key].Increment();
        }
    }
}